import { 
  app, 
  BrowserWindow, 
  dialog, 
  ipcMain, 
  nativeImage, 
  Tray,
  Menu,
  globalShortcut, // 全局快捷键
  Notification
} from "electron";
import { fileURLToPath } from "node:url";
import path from 'node:path'
import * as fs from "node:fs"
import mimeType from "mime-types"

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const windowObj = {}


const createMainWindow = function () {
  windowObj.mainWindow= new BrowserWindow({
    width: 800,
    height: 600,
    show: false,
    webPreferences: {
      webSecurity:false, // 阻止渲染进程跨域
      preload: path.join(__dirname, 'preload.mjs')
    }
  })
  windowObj.mainWindow.setMenu(null) // 隐藏设置菜单栏
  windowObj.mainWindow.maximize() // 初始化屏幕最大化（不是全屏）
  windowObj.mainWindow.webContents.send('currentWindow', 'mainWindow')
  // 在开发环境默认打开控制台
  if (process.env.NODE_ENV === 'development') {
    windowObj.mainWindow.webContents.openDevTools()
  }
  // 优化放大屏幕闪烁问题
  windowObj.mainWindow.once('ready-to-show', () => {
    windowObj.mainWindow.show();
  })
  windowObj.mainWindow.on('close', (event) => {
    event.preventDefault()
    windowObj.mainWindow.hide()
  })
  // 同步读取文件
  ipcMain.handle('readFileSync', (_, url, encoding='utf8') => {
    return fs.readFileSync(path.join(__dirname, url), {
      encoding
    })
  })
  // 读取全局文件
  ipcMain.handle('readSystemFile', (_, url, encoding='utf8') => {
    return new Promise( (resolve) => {
      fs.readFile(path.join(url), {
        encoding
      }, (err, data) => {
        resolve({
          err,data
        })
      })
    })
    
  })
  ipcMain.handle('writeSystemFile', (_, url, data, encoding='utf8') => {
    return new Promise( (resolve) => {
      fs.writeFile(path.join(url), data, {
        encoding
      }, (err) => {
        resolve(err)
      })
    })
    
  })
  // 删除系统文件
  ipcMain.handle('deleteSystemFile', (_, url) => {
    return new Promise( (resolve) => {
      fs.unlink(path.join(url), (err) => {
        if (err !== null) {
          rejects(err)
        } else {
          resolve()
        }
      })
    })
    
  })
  // 追加分片文件
  ipcMain.handle('appendSystemFile', (_, url, data, encoding='utf8') => {
    return new Promise( (resolve) => {
      fs.appendFile(path.join(url), data, {
        encoding
      }, (err) => {
        resolve(err)
      })
    })
    
  })
  // 重写文件
  ipcMain.handle('writeFileSync', (_, url, data, encoding='utf8') => {
    return fs.writeFileSync(path.join(__dirname, url), data, {
      encoding
    })
  })
  // 
  ipcMain.handle('existsSync', (_, url, data, encoding='utf8') => {
    return fs.existsSync(path.join(__dirname, url))
  })
  // 消息
  ipcMain.handle('message', (_, title, message, type='info') => {
    return dialog.showMessageBox(windowObj.mainWindow, {
      type,
      title,
      message,
      buttons: ['确定', '取消'],
    })
  })
  const devTools = (win) => {
    if (process.env.NODE_ENV === 'development') {
      const current = windowObj[win]
      if (current.webContents.isDevToolsOpened()) {
        current.webContents.closeDevTools()
      } else {
        current.webContents.openDevTools()
      }
    }    
  }
  ipcMain.on('win', (_, win, type, ...args) => {
    switch (type) {
      case 'devTools':
        devTools(win)
        break;
      case 'hide':
        windowObj[win].hide()
        break;
    }
  })
  ipcMain.handle('getFile', (_, opt={}) => {
    return dialog.showOpenDialog({
      title: opt.title ?? "",
      defaultPath: opt.defaultPath ?? "",
      filters: opt.filters ?? [
        {
          name: 'All Files',
          extensions: ['*']  // 允许选择所有文件类型
        }
      ],
      properties: opt.properties ?? ['openFile'], // 默认单选文件
      buttonLabel: opt.buttonLabel ?? ""
    })
  })
  // 获取文件类型
  ipcMain.handle('getFileType', (_, name) => {
    return mimeType.lookup(name)
  })
  // 根据文件路径获取文件名
  ipcMain.handle('getFileBasename', (_, name) => {
    return path.basename(name)
  })
  // 保存文件
  ipcMain.handle('saveFile', (_, opt={}) => {
    return dialog.showSaveDialog({
      title:opt.title ?? '',
      defaultPath:opt.defaultPath ?? '',
      filters:opt.filters ?? [],
      properties:opt.properties ?? [],
      buttonLabel:opt.buttonLabel ?? ''
    })
  })
  if (process.env.NODE_ENV === 'development') {
    windowObj.mainWindow.loadURL(process.env['VITE_DEV_SERVER_URL'])
  } else {
    windowObj.mainWindow.loadFile(path.join(__dirname, "./index.html"))
  }
}
ipcMain.on('runApp', (_, appData) => {
  if (!windowObj.app) {
    windowObj.app = {}
  }
  const appPath = path.join(__dirname, "micro-app", appData.packageName)
  if (windowObj.app[appData.packageName]) {
    windowObj.app[appData.packageName].show()
    return
  }
  let webPreferences = {}
  // 是否可调用API
  if (appData.preload) {
    webPreferences.preload = path.join(__dirname, 'microApp.preload.js')
  }
  windowObj.app[appData.packageName] = new BrowserWindow({
    title: appData.title,
    width: appData.width,
    height: appData.height,
    resizable: appData.resize ?? false,
    show: false,
    webPreferences: {
      ...webPreferences,
      webSecurity:false, // 阻止渲染进程跨域
    }
  })
  // 小窗口默认打开控制台
  // windowObj.app[appData.packageName].webContents.openDevTools()
  if (appData.ua) {
    windowObj.app[appData.packageName].webContents.setUserAgent(appData.ua)
  }
  if (appData.type === 'remote') {
    windowObj.app[appData.packageName].loadURL(appData.path)
  } else {
    windowObj.app[appData.packageName].loadFile(path.join(appPath, appData.path))
  }
  // 拦截重新打开新窗口
  windowObj.app[appData.packageName].webContents.setWindowOpenHandler((detail) => {
    if (appData.type === 'remote') {
      windowObj.app[appData.packageName].loadURL(detail.url)
    } else {
      windowObj.app[appData.packageName].loadFile(detail.url)
    }
  })
  windowObj.app[appData.packageName].setMenu(null)
  windowObj.app[appData.packageName].on('ready-to-show', () => {
    windowObj.app[appData.packageName].show()
  })
  windowObj.app[appData.packageName].on('close', () => {
    windowObj.app[appData.packageName] = null
  })
})
ipcMain.on('notify', (_, opt) => {
  if (opt.icon) {
    opt.icon = nativeImage.createFromPath(path.join(__dirname, opt.icon))
  }
  const notify = new Notification(opt)
  notify.show()
})
if(process.platform === 'darwin'){
  
  // 在macOS环境才执行
  app.on('activate', () => {
    if (windowObj.mainWindow) {
      windowObj.mainWindow.show()
    }
  })
}
app.whenReady().then( res => {
  const icon = nativeImage.createFromPath(path.join(__dirname, "snake.png"))
  const tray = new Tray(icon)
  const logo = nativeImage.createFromPath(path.join(__dirname, "logo.png"))
  app.dock.setIcon(logo) // 在Mac电脑中
  tray.on('click', () => {
    windowObj.mainWindow.show()
  })
  const contextMenu = Menu.buildFromTemplate([
    {
      label: "打开主界面",
      click: () => {
        windowObj.mainWindow.show()
        // windowObj.mainWindow.restore()
      }
    },
    {
      label: "退出",
      click: () => {
        app.exit()
      }
    }
  ])
  tray.setContextMenu(contextMenu)
  tray.setToolTip("GINO")
  if (process.platform === 'darwin') {
    app.dock.setMenu(contextMenu)
  }
  globalShortcut.register('CommandOrControl+Shift+O', () => {
    windowObj.mainWindow.show()
    windowObj.mainWindow.maximize()
  })
  createMainWindow()
})
